﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AppEnvironment.Lib;
using DPM.Dto;
using DPM.Dto.LoadView;
using AppEnvironment;
using DPM.Presenters.Data;
using DPM.Common;
using DPM.Common.Helpers;

namespace DPM.Presenters
{
	public class CreateMemberPresenter : Presenter
	{
		public event Action<LoadCreateMemberViewDto> OnLoadView = delegate { };

		protected override void Init(bool isFirstTime)
		{
			base.Init(isFirstTime);
		}
		protected override void Load(bool isFirstTime)
		{
			if (isFirstTime)
			{
				OnLoadView(PopulateView());
			}
		}
		public void Submit(MemberDto dto)
		{
			DPMDataDataContext data = new DPMDataDataContext();

			#region Member Details
			Member newMem = new Member
			{
			 FirstName = dto.FistName,
			 LastName = dto.LastName,
			 IDNumber = dto.IdNumber,
			 Title = dto.Title,
			 EmailAddress = dto.EmailAddress,
			 EmergencyContactPerson = dto.ContactEmergency,
			 MemberType = dto.MemberType,
			 StartDate = DateTime.Today.ToString(),
			 ParentId = -1,
			 JobTitle = dto.JobTitle,
			 UserId = 1,
			 MartialArtsBackground = dto.MartialArtsBackground,
			 DateOfBirth = dto.DateOfBirth.ToString(),
			 GuardianContactNumber = dto.GuardianContactNumber,
			 GuardianName = dto.GuardianName,
			 GuardianIdNumber = dto.GuardianIDNumber,
			 ContractType = dto.ContractType,
			 ExpiryDate = DateTime.Today.AddYears(1).ToString(),
			
			};

			//TODO: add the expiry date logic based on contract type
			data.Members.InsertOnSubmit(newMem);
			data.SubmitChanges();
			#endregion Member Details

			#region Contact Numbers
			List<Contact> memberContacts = new List<Contact>();

			if (!string.IsNullOrEmpty(dto.ContactHome))
			{
				
				Contact contactHome = new Contact
				{
					ContactNumber = dto.ContactHome,
					ContactType = (from ct in data.ContactTypes
								   where ct.Type == "Home"
								   select ct.ContactTypeID).FirstOrDefault(),
					MemberId = newMem.MemberID,
				};
				memberContacts.Add(contactHome);
			}

			if (!string.IsNullOrEmpty(dto.ContactCell))
			{
				Contact contactCell = new Contact
				{
					ContactNumber = dto.ContactCell,
					ContactType = (from ct in data.ContactTypes
								   where ct.Type == "Cell"
								   select ct.ContactTypeID).FirstOrDefault(),
					MemberId = newMem.MemberID,
				};
				memberContacts.Add(contactCell);
			}

			if (!string.IsNullOrEmpty(dto.ContactWork))
			{
				Contact contactWork = new Contact
				{
					ContactNumber = dto.ContactWork,
					ContactType = (from ct in data.ContactTypes
								   where ct.Type == "Work"
								   select ct.ContactTypeID).FirstOrDefault(),
					MemberId = newMem.MemberID,
				};
				memberContacts.Add(contactWork);
			}

			if (!string.IsNullOrEmpty(dto.ContactFax))
			{
				Contact contactFax = new Contact
				{
					ContactNumber = dto.ContactWork,
					ContactType = (from ct in data.ContactTypes
								   where ct.Type == "Fax"
								   select ct.ContactTypeID).FirstOrDefault(),
					MemberId = newMem.MemberID,
				};
				memberContacts.Add(contactFax);
			}

			data.Contacts.InsertAllOnSubmit(memberContacts);
			data.SubmitChanges();
			#endregion Contact Numbers

			#region Address Details
			List<AddressDetail> memberAddresses = new List<AddressDetail>();
			if (AddressPopulated(dto.HomeAddress))
			{
				AddressDetail homeAdderess = new AddressDetail
				{
					AddressLine1 = dto.HomeAddress.AddressLine1,
					AddressLine2 = dto.HomeAddress.AddressLine2,
					AddressType = (from t in data.AddressTypes
								   where t.Type == "Residential"
								   select t.AddressTypeID).FirstOrDefault(),
					City = dto.HomeAddress.City,
					Country = "South Africa",
					Region = dto.HomeAddress.Region,
				};

				data.AddressDetails.InsertOnSubmit(homeAdderess);
				data.SubmitChanges();

				MemberAddressRelation memberWorkRelation = new MemberAddressRelation
				{
					AddressId = homeAdderess.AddressDetailsID,
					MemberId = newMem.MemberID,
				};

				data.MemberAddressRelations.InsertOnSubmit(memberWorkRelation);
				data.SubmitChanges();
			}
	

			#endregion Address Details

			#region Work Details
			CompanyDetail companyDetail = new CompanyDetail
			{
				CompanyName = dto.CompanyName,
				ContactNumber = dto.ContactWork,
				ContactPerson = dto.CompanyContactPerson,
				Industry = dto.Industry,
			};

			data.CompanyDetails.InsertOnSubmit(companyDetail);
			data.SubmitChanges();

			CompanyMemberRelation companyMemRelation = new CompanyMemberRelation
			{
				CompanyId = companyDetail.CompanyID,
				MemberId = newMem.MemberID,
			};

			data.CompanyMemberRelations.InsertOnSubmit(companyMemRelation);
			

			if (AddressPopulated(dto.WorkAddress))
			{
				AddressDetail workAdderess = new AddressDetail
				{
					AddressLine1 = dto.WorkAddress.AddressLine1,
					AddressLine2 = dto.WorkAddress.AddressLine2,
					AddressType = (from t in data.AddressTypes
								   where t.Type == "Business"
								   select t.AddressTypeID).FirstOrDefault(),
					City = dto.WorkAddress.City,
					Country = "South Africa",
					Region = dto.WorkAddress.Region,
				};

				data.AddressDetails.InsertOnSubmit(workAdderess);
				data.SubmitChanges();

				MemberAddressRelation memberWorkRelation = new MemberAddressRelation
				{
					AddressId = workAdderess.AddressDetailsID,
					MemberId = newMem.MemberID,
				};

				data.MemberAddressRelations.InsertOnSubmit(memberWorkRelation);
				
			}

			#endregion Work Details

			#region Training Details
			var memClassRelation = from mcr in dto.Classes
								   select new MemberClassRelation
								   {
									   ClassId = mcr,
									   MemberId = newMem.MemberID,
								   };
			data.MemberClassRelations.InsertAllOnSubmit(memClassRelation);
			#endregion Training Details

			#region Medical Infromation
			MedicalHistory medicalDetails = new MedicalHistory
			{
				MedicalAidNumber = dto.MedicalAidNumber,
				MedicalAidProvider = dto.MedicalAidProvider,
				MedicalDescription = dto.MedicalConditionDescription,
				DoctorName = dto.DoctorName,
				ContactNumber = dto.ContactMedical,
				MemberId = newMem.MemberID,
				HighLowBloodPressure = false,
			    Allergies = false,
				Asthma = false,
				BrokenBones = false,
				Operations = false,
				Other = string.Empty,
			};

			foreach (int i in dto.Classes)
			{
				if (i == Enums.MedicalConditionsEnum.HighLowBloodPressure.As<int>(0))
				{
					medicalDetails.HighLowBloodPressure = true;
				}

				if (i == Enums.MedicalConditionsEnum.Allergies.As<int>(0))
				{
					medicalDetails.Allergies = true;
				}

				if (i == Enums.MedicalConditionsEnum.Asthma.As<int>(0))
				{
					medicalDetails.Asthma = true;
				}

				if (i == Enums.MedicalConditionsEnum.BrokenBones.As<int>(0))
				{
					medicalDetails.BrokenBones = true;
				}

				if (i == Enums.MedicalConditionsEnum.Operations.As<int>(0))
				{
					medicalDetails.Operations = true;
				}
			}

			data.MedicalHistories.InsertOnSubmit(medicalDetails);
			#endregion Medical Information

			#region Banking Information
			PaymentDetail bankingDetails = new PaymentDetail
			{
				NameOfBank = dto.BankName,
				AccountHolderName = dto.AccountHolder,
				BranchCode = dto.BranchCode,
				BranchName = dto.BranchName,
				AccountType = dto.AccountType,
				AccountNumber = dto.AccountNumber,
				AmountPayable = dto.AmountPayable.As<decimal>(0),
				ContractType = dto.ContractType,
				MemberId = newMem.MemberID,

			};
			
			data.PaymentDetails.InsertOnSubmit(bankingDetails);
			#endregion Banking Information

			#region Misc Data
			
			#endregion Misc Data

			data.SubmitChanges();
		}
		private LoadCreateMemberViewDto PopulateView()
		{
			DPMDataDataContext data = new DPMDataDataContext();
			LoadCreateMemberViewDto dto = new LoadCreateMemberViewDto
			{
				Titles = from t in data.MemberTitles
						 select new IdNameDto {Id= t.MemberTitleId, Name=t.Title},
				MemberTypes = from mt in data.MemberTypes
							  select new IdNameDto { Id = mt.MemberTypeID, Name = mt.Type },
				AccountType = from at in data.AccountTypes
							  select new IdNameDto { Id = at.AccountTypeID, Name = at.Type },
				AdvertisementSource = from adv in data.AdvertisementTypes
									  select new IdNameDto { Id = adv.AdvertisementTypeID, Name = adv.Type },
				ContractType = from ct in data.ContractTypes
							   select new IdNameDto { Id = ct.ContractTypeID, Name = ct.Type },
				Industry = from i in data.Industries
						   select new IdNameDto { Id = i.IndustryID, Name = i.IndustryName },
				Regions = from r in data.Regions
						  select new IdNameDto { Id = r.RegionID, Name = r.RegionName },
				MedicalConditions = Common.Helpers.MedicalHelper.GetMedicalConditions(),
				Classes = from c in data.Classes
						  select new IdNameDto
						  {
							  Id = c.ClassID,
							  Name = c.Name + " " + (from cd in data.ClassDays
													 where cd.ClassDaysID == c.ClassDays
													 select cd.Days).FirstOrDefault(),
						  },
			};
			
			return dto;
		}
		private bool AddressPopulated(AddressDto dto)
		{
			bool isValid = true;
			if (string.IsNullOrEmpty(dto.AddressLine1))
			{ 
			isValid = false;
			}
			if (string.IsNullOrEmpty(dto.AddressLine2))
			{ 
			isValid = false;
			}
			if(string.IsNullOrEmpty(dto.City))
			{
				isValid = false;
			}
			return isValid;
		}
	}
}
